<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 17/2/22
 * Time: 15:52
 */

namespace Warehouse\Service;

use Inbound\Service\PublicInfoService;
use Warehouse\Model\PurchaseOrderDetailsModel;
use Warehouse\Model\PurchaseOrderDetailsSitesModel;
use Warehouse\Model\RecieveDetailsModel;


use Warehouse\Model\UnqualifiedDealInvoicesModel;

class CheckOrdersService
{

    public $recieveDetails = null;
    public $attrLog        = null;

    //查询记录总数
    public $count = 0;
    //页面展示包含页面样式
    public $page = array();
    //数据
    public $data = array();

    public $checkorders_details_data = array();

    public $nowtime;

    /**
     * CheckOrdersService constructor.
     *
     * @param string $table
     * @param array  $param
     */
    public function __construct($table = '', $param = array())
    {
        $this->nowtime             = date('Y-m-d H:i:s', time());
        $this->recieveDetails      = D('RecieveDetails', 'Model');
        $this->attrLog             = D('AttrLog', 'Model');
        $this->checkQualityDetails = D('CheckQualityDetails', 'Model');
    }

    /**
     * 获取所有的质检数据
     *
     * @param array $_array
     * @param bool  $flag
     *
     * @return array
     */
    public function select($_array = array(), $flag = true)
    {
        $_array = empty($_array) ? $_GET : $_array;
        $model  = $this->checkQualityDetails->get_check_details_model($_array, $flag);
        if ($flag) {
            $checkQualityDetails = clone $model;
            $this->count         = $checkQualityDetails->count();//数量
            $Page                = new \Org\Util\Page($this->count, 20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
            $this->page          = $Page->show();// 分页显示输出

            $model->order("id asc")
                ->limit($Page->firstRow.','.$Page->listRows);
        }

        $result = $model->join(
            'wms_purchaseorder_details ON wms_purchaseorder_details.purchaseorder_id=wms_check_quality_details.purchaseorder_id 
            AND wms_purchaseorder_details.sku=wms_check_quality_details.sku',
            'LEFT'
        )
            ->field('wms_check_quality_details.*,wms_purchaseorder_details.quantity')
            ->select();
        $result            = $this->get_all_position_by_sku($result,1);
        $results           = $this->addPublicData();
        $results['result'] = $result;
        return $results;
    }

    /**
     * @param $results
     * @return mixed
     * 获取sku所有储位
     */
    public function get_all_position_by_sku($results,$flag){
        if($results){
            $sku_arr = PublicdataService::i_array_column($results,'sku');
            $skus = implode(',',$sku_arr);
            $positions = M('storage_sku','wms_','fbawarehouse')
                ->where(array('sku'=>array('in',$skus)))
                ->getField('id,sku,storage_position');
            $temp_position = array();
            foreach($positions as $key=>$position){
                $temp_sku = $position['sku'];
                if($position['sku'] == $temp_sku){
                    if($flag){
                        $temp_position[$position['sku']].=$position['storage_position'].'<br/>';
                    }else{
                        $temp_position[$position['sku']].=$position['storage_position']."\n";
                    }

                }
            }
            $temp_arr = array();
            foreach($results as $result){
                $result['storage_position'] = $temp_position[$result['sku']];
                $temp_arr[] = $result;
            }
            return $temp_arr;
        }else{
            return $results;
        }

    }

    /**
     * 添加一些公共数据
     *
     * @return array
     */
    public function addPublicData()
    {
        $results = array();

        $results['users']               = PublicdataService::get_user_names();
        $results['enterprise_dominant'] = PublicdataService::get_enterprise_dominants();
        $results['rebate']              = PublicdataService::get_export_tax_rebate();
        $results['suppliers']           = PublicdataService::get_suppliers();

        return $results;
    }

    /**
     * 合计
     *
     * @param array $_array
     * @param bool  $flag
     *
     * @return mixed
     */
    public function summary(&$_array = array(), $flag = true)
    {
        $model = $this->checkQualityDetails->get_check_details_model($_array, $flag);

        $result = $model->field(
            'SUM(check_quantity) AS totalcheck, SUM(qualified_quantity) AS totalquality, SUM(unquality_count) AS totalunquality'
        )
            ->find();

        return $result;
    }

    /**
     * 根据条件获取所有信息
     *
     * @param array $_array
     * @param bool  $flag
     *
     * @return array
     */
    public function getAllInfo(&$_array = array(), $flag = true)
    {
        $_array = empty($_array) ? $_GET : $_array;
        $model  = $this->checkQualityDetails->get_check_details_model($_array, $flag);
        $result = $model->join(
            'wms_purchaseorder_details ON wms_purchaseorder_details.purchaseorder_id=wms_check_quality_details.purchaseorder_id 
            AND wms_purchaseorder_details.sku=wms_check_quality_details.sku',
            'LEFT'
        )
            ->order("id asc")
            ->field('wms_check_quality_details.*,wms_purchaseorder_details.quantity')
//            ->where('wms_check_quality_details.qualified_quantity>0')
            ->select();
        $result            = $this->get_all_position_by_sku($result,0);
        $results           = $this->addPublicData();
        $results['result'] = $result;

        return $results;
    }

    /**
     * @param array $_array
     * @param bool  $flag
     *
     * @return mixed
     * 质检报表数据查询与显示,以采购单为单位
     */
    public function getCheckDetails($_array = array(), $flag = true)
    {
        $_array = empty($_array) ? $_GET : $_array;
        $model  = $this->checkQualityDetails->get_check_details_model($_array, $flag);
        if ($flag) {
            $checkQualityDetails = clone $model;
            $this->count         = $checkQualityDetails->getField('COUNT(DISTINCT(purchaseorder_id)) as count');//数量
            $Page                = new \Org\Util\Page($this->count, 20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
            $this->page          = $Page->show();// 分页显示输出

            $purchase_ids = $checkQualityDetails->group('purchaseorder_id')
                ->where($_array)
                ->order('invoice_date DESC')
                ->limit($Page->firstRow.','.$Page->listRows)
                ->getField('purchaseorder_id, purchaseorder_id AS purchaseorder_id2');

            if ($purchase_ids) {
                $model->where(
                    array(
                        'purchaseorder_id' => array(
                            'IN',
                            $purchase_ids
                        )
                    )
                )
                    ->order("invoice_date desc");
            }
        }

        $result = $model->select();

        $data = array();
        $sites = PublicInfoService::get_site_array();
        foreach ($result as $key => &$value) {
            $value['site_id'] = $sites[$value['site_id']];
            $data[$value['purchaseorder_id']][] = $value;
        }
        $results['result']       = $data;
        $results['users']        = PublicdataService::get_user_names();
        $results['print_status'] = array(
            '0' => '未打印',
            '1' => '已打印',
        );

        return $results;
    }

    /**
     * @param array $_array
     *
     * @return mixed
     * 质检报表数据查询与显示
     */
    public function getCheckQualityDetails($_array = array())
    {
        $_array = empty($_array) ? $_GET : $_array;
        $model  = $this->checkQualityDetails->get_check_details_model($_array);

        $result = $model->find();

        return $result;
    }

    /**
     * 根据id获取收货明细单详情
     *
     * @param $id
     *
     * @return mixed
     */
    public function getReceiveDetailById($id)
    {
        $sites = PublicInfoService::get_site_array();
        $data                       = $this->recieveDetails->get_recieve_details_by_id($id);
        $data['transfer_hopper_id'] = PublicdataService::get_transfer_hopper_name($data['transfer_hopper_id']);
        $data['supplier']           = PublicdataService::get_supplier_name($data['supplier']);
        $data['check_man']          = PublicdataService::get_user_name($data['user_id']);
        $data['site_id']            = $sites[$data['site_id']];

        return $data;
    }

    /**
     * 更新sku的物流属性,调用skusystem的接口
     *
     * @param $_array
     */
    public function updateAttr(&$_array)
    {
        if (!empty($_array['skuLogistic']) && $_array['skuLogistic'] != 'undefined') {
            $logicArr = array(strtoupper($_array['sku']) => $_array['skuLogistic']);
            ApiSkusystemService::updateSkuArrAttr($logicArr);
        }

        $this->attrLog->addLog($_array);
        $this->recieveDetails->updateLogisticsCheck($_array['sku']);
    }

    /**
     * 根据收货明细单id获取扫描质检的所有数据
     *
     * @param $id
     *
     * @return mixed
     */
    public function getScanCheckDetailById($id)
    {
        $result = $this->recieveDetails->getScanCheckInfoById($id);

        return $result;
    }

    /**
     * 根据条件获取sku质检标准确认信息
     *
     * @param $_array
     *
     * @return mixed
     */
    public function getCheckStandardDetail(&$_array)
    {
        $model = $this->recieveDetails;
        $sites = PublicInfoService::get_site_array();
        $result['result'] = $model->getCheckStandardDetail($_array);
        $result['users']  = PublicdataService::get_user_names();
        $result['rebate'] = PublicdataService::get_export_tax_rebate();
        foreach($result['result'] as &$res){
            $res['site_id'] = $sites[$res['site_id']];
        }
        return $result;
    }

    /**
     * 质检标准确认
     *
     * @param $_array
     */
    public function checkSkuStandard(&$_array)
    {
        $model = $this->recieveDetails;

        return $model->checkSkuStandard($_array);
    }

    /**
     * 获取扫描质检详情
     *
     * @param $_array
     *
     * @return mixed
     */
    public function getScanCheckDetail(&$_array)
    {
        $model = $this->recieveDetails;
        $sites = PublicInfoService::get_site_array();

        $result['result']       = $model->getScanCheckDetail($_array);
        foreach($result['result'] as &$res){
            $res['site_id'] = $sites[$res['site_id']];
        }
        $result['suppliers']    = PublicdataService::get_suppliers();
        $result['rebate']       = PublicdataService::get_export_tax_rebate();
        $result['warehouses']   = PublicdataService::get_warehouse_names();
        $result['skuchecksign'] = array(
            '0'  => '无需确认',
            '10' => '待确认',
            '20' => '已确认',
        );
        return $result;
    }

    /**
     * 扫描质检保存与数据回写
     *
     * @param $_array
     *
     * @return bool
     */
    public function scanCheckSave(&$_array)
    {
        $model                           = $this->checkQualityDetails;
        $receiveDetailsModel             = new RecieveDetailsModel();
        $purchaseOrderDetailsModel       = new PurchaseOrderDetailsModel();
        $unqualifiedDealInvoicesModel    = new UnqualifiedDealInvoicesModel();
        $purchaseOrderDetailsSitesModel  = new PurchaseOrderDetailsSitesModel();

        $id                                     = array(
            $_array['receiveDetailId']
        );
        $scanCheckData                          = $receiveDetailsModel->getScanCheckInfoById($id);
        $scanCheckData[0]['sku_standard']       =
            empty($scanCheckData[0]['sku_standard']) ? '' : $scanCheckData[0]['sku_standard'];
        $scanCheckData[0]['invoice_date']       = date('Y-m-d H:i:s', time());
        $scanCheckData[0]['check_man']          = $_SESSION['current_account']['id'];
        $scanCheckData[0]['qualified_quantity'] = $_array['qualifiedNum']?$_array['qualifiedNum']:0;
        $scanCheckData[0]['check_quantity']     = $_array['checkNum'];
        $scanCheckData[0]['unquality_count']    = empty($_array['unqualifiedNum']) ? 0 : $_array['unqualifiedNum'];
        $scanCheckData[0]['remark']             =
            empty($_array['unqualifiedReason']) ? '' : $_array['unqualifiedReason'];

        $check_quality_details_id = $model->addAll_check_quality_details($scanCheckData);

        if ($check_quality_details_id) {
            //扫描质检保存后,回写质检数量到收货明细单
            $map  = array(
                'id' => $_array['receiveDetailId'],
            );
            $data = array(
                'check_count' => $_array['checkNum'],
            );
            //回写收货明细单
            $receiveDetailsModel->update_recieve_details($map, $data);

            //回写采购明细站点表
            $sites_map = array(
                'purchaseorders_id' => $scanCheckData[0]['purchaseorder_id'],
                'sku'               => $scanCheckData[0]['sku'],
                'site_id'           => $scanCheckData[0]['site_id'],
            );
            $sites_data = array(
                'check_quantity'  =>$_array['checkNum'],
                'return_quantity' =>empty($_array['unqualifiedNum']) ? 0 : $_array['unqualifiedNum'],
            );
            $purchaseOrderDetailsSitesModel->setInc_purchaseorder_details_sites($sites_map, array (
                'column' => 'check_quantity',
                'data'   => $sites_data['check_quantity']
            ));
            $purchaseOrderDetailsSitesModel->setInc_purchaseorder_details_sites($sites_map, array (
                'column' => 'return_quantity',
                'data'   => $sites_data['return_quantity']
            ));

            //回写采购明细单
            $map2          = array(
                'purchaseorder_id' => $scanCheckData[0]['purchaseorder_id'],
                'sku'              => $scanCheckData[0]['sku'],
            );
            $purchaseOrder = $purchaseOrderDetailsModel->get_purchaseorder_details_model($map2)
                ->field('quantity,check_quantity,return_quantity,status')
                ->find();
            $data2 = array(
                'check_quantity'  => $purchaseOrder['check_quantity'] + $scanCheckData[0]['check_quantity'],
                'return_quantity' => $purchaseOrder['return_quantity'] + $scanCheckData[0]['unquality_count'],
            );
            if($purchaseOrder['status']==50 && $data2['check_quantity']>=$purchaseOrder['quantity']){
                $data2['status'] = 60;
            }
            //回写采购详情单
           $purchaseOrderDetailsModel->update_purchaseorder_details($map2, $data2);

            if ($_array['unqualifiedNum']) {
                $unqualifiedDealInvoicesData['check_detail_id']     = $check_quality_details_id;
                $unqualifiedDealInvoicesData['warehouseid']         = $scanCheckData[0]['warehouseid'];
                $unqualifiedDealInvoicesData['invoice_date']        = $scanCheckData[0]['invoice_date'];
                $unqualifiedDealInvoicesData['purchaseorder_id']    = $scanCheckData[0]['purchaseorder_id'];
                $unqualifiedDealInvoicesData['sku']                 = $scanCheckData[0]['sku'];
                $unqualifiedDealInvoicesData['sku_name']            = $scanCheckData[0]['sku_name'];
                $unqualifiedDealInvoicesData['sku_standard']        = $scanCheckData[0]['sku_standard'];
                $unqualifiedDealInvoicesData['storage_position']    = $scanCheckData[0]['storage_position'];
                $unqualifiedDealInvoicesData['supplier']            = $scanCheckData[0]['supplier_id'];
                $unqualifiedDealInvoicesData['check_time']          = $scanCheckData[0]['invoice_date'];
                $unqualifiedDealInvoicesData['quantity']            = $scanCheckData[0]['unquality_count'];
                $unqualifiedDealInvoicesData['quality_man']         = $_SESSION['current_account']['id'];
                $unqualifiedDealInvoicesData['quality_remark']      = $scanCheckData[0]['remark'];
                $unqualifiedDealInvoicesData['purchase_man']        = $scanCheckData[0]['purchase_id'];
                $unqualifiedDealInvoicesData['enterprise_dominant'] = $scanCheckData[0]['enterprise_dominant'];
                $unqualifiedDealInvoicesData['export_tax_rebate']   = $scanCheckData[0]['export_tax_rebate'];
                $unqualifiedDealInvoicesData['transfer_hopper_id']  = $scanCheckData[0]['transfer_hopper_id'];
                $unqualifiedDealInvoicesData['transfer_type']       = $scanCheckData[0]['transfer_type'];
                $unqualifiedDealInvoicesData['store']               = $scanCheckData[0]['store'];
                $unqualifiedDealInvoicesData['site_id']             = $scanCheckData[0]['site_id'];

                //生成不良品单
                $unqualifiedDealInvoicesModel->add_unqualified_deal_invoices($unqualifiedDealInvoicesData);
            }
        }

        return true;
    }

    /**
     * @param $receive_detail_id
     * @return mixed
     * 根据收货明细id获取对应质检单的入库数量
     */
    public function get_stockin_num($receive_detail_id){
        return $this->checkQualityDetails->checkQualityDetails
            ->where(array('recieve_detail_id'=>$receive_detail_id))
            ->field('id,stockin_num,check_quantity,unquality_count,purchaseorder_id,sku,site_id')
            ->select();
    }

    /**
     * @param $receive_detail_id
     * @return mixed
     * 判断是否不良品出库
     */
    public function get_bad_product_delivery($check_detail_id){
        return M('bad_product_delivery','wms_','fbawarehouse')
            ->where(array('check_detail_id'=>$check_detail_id))
            ->count(0);
    }

    /**
     * @param $receive_detail_id
     * @param $check_info
     * 修改
     *
     */
    public function  reset_num($receive_detail_id,$check_info){
        $receiveDetailsModel            = new RecieveDetailsModel();
        $purchaseOrderDetailsModel      = new PurchaseOrderDetailsModel();
        $purchaseOrderDetailsSitesModel = new PurchaseOrderDetailsSitesModel();
        //1.将收货明细表中的质检数量置为0
        $map  = array(
            'id' => $receive_detail_id,
        );
        $data = array(
            'check_count' =>0,
        );
        $res = $receiveDetailsModel->update_recieve_details($map, $data);

        //2.将采购明细表中的质检数量，不合格量置为0
        $map2          = array(
            'purchaseorder_id' => $check_info[0]['purchaseorder_id'],
            'sku'              => $check_info[0]['sku'],
        );
        $purchaseOrder = $purchaseOrderDetailsModel->get_purchaseorder_details_model($map2)
            ->field('check_quantity,return_quantity,status')
            ->find();
        $data2 = array(
            'check_quantity'  => $purchaseOrder['check_quantity'] - $check_info[0]['check_quantity'],
            'return_quantity' => $purchaseOrder['return_quantity'] - $check_info[0]['unquality_count'],
        );
        if($purchaseOrder['status'] == 60){
            $data2['status']  = 50;
        }
        $res2 = $purchaseOrderDetailsModel->update_purchaseorder_details($map2, $data2);

        //3.回写采购明细站点表
        $sites_map = array(
            'purchaseorders_id' => $check_info[0]['purchaseorder_id'],
            'sku'               => $check_info[0]['sku'],
            'site_id'           => $check_info[0]['site_id'],
        );
        $sites_data = array(
            'check_quantity'  =>$check_info[0]['check_quantity'],
            'return_quantity' =>$check_info[0]['unquality_count'],
        );
        $purchaseOrderDetailsSitesModel->setDec_purchaseorder_details_sites($sites_map, array (
            'column' => 'check_quantity',
            'data'   => $sites_data['check_quantity']
        ));
        $purchaseOrderDetailsSitesModel->setDec_purchaseorder_details_sites($sites_map, array (
            'column' => 'return_quantity',
            'data'   => $sites_data['return_quantity']
        ));

        //4.删除本条质检明细
        $res3 = $this->checkQualityDetails->checkQualityDetails
            ->where(array('id'=>$check_info[0]['id']))
            ->delete();

        //5.删除不良品出库id
        $res4 = true;
        if ($check_info[0]['unquality_count']!=0){
            $bad_product_delivery_model = M('unqualified_deal_invoices','wms_','fbawarehouse');
            $res4 = $bad_product_delivery_model->where(array('check_detail_id'=>$check_info[0]['id']))
                ->delete();
        }

        if($res && $res2 && $res3 && $res4){
            return true;
        }else{
            return false;
        }

    }

    /**
     * @param $sku
     * @return mixed
     * 根据sku获取物流属性
     */
    public function get_logic_v($sku){
        $logic_v = $this->attrLog->attrLog
            ->where(array('sku'=>$sku))
            ->limit(1)
            ->getField('logic_v');
        if(empty($logic_v)){
            $model = M('skusystem_sku_logic', ' ', 'fbawarehouse');
            $logic_v = $model
                ->where(array('sku'=>$sku))
                ->limit(1)
                ->getField('logic_attr');
        }
        return $logic_v;
    }


    /**
     * 打印相同采购单下的质检单
     *
     * @param array $_array
     *
     * @return array
     */
    public function print_quality_report(&$_array = array(), $call = false)
    {
        $model     = $this->checkQualityDetails;
        $check_ids = explode('-', $_array['ids']);
        if (!empty($_array['po_id'])) {
            $where_map = array(
                'wms_check_quality_details.id'               => array(
                    'IN',
                    $check_ids
                ),
                'wms_check_quality_details.purchaseorder_id' => $_array['po_id'],
            );
        } else {
            $where_map = array(
                'wms_check_quality_details.id' => array(
                    'IN',
                    $check_ids
                ),
            );
        }
        $result = $model->get_check_detail_and_purchase_info($where_map);

        $inventoryS = new InventoryService();
        foreach ($result as &$_result) {
            //增加了站点和主体
            $condition = array(
                'sku'=>$_result['sku'],
                'enterprise_dominant'=>$_result['enterprise_dominant'],
                'site_id'=>$_result['site_id']);
            //出口退税总可用库存
            $_result['tax_all_available_num'] = $inventoryS->getTaxInventoriesInfo($condition);
            //非出口退税总可用库存
            $_result['all_available_num'] = $inventoryS->getInventoriesInfo($condition);
        }

        if ($call) {
            return $result;
        }

        $results['result']   = $result;
        $results['evidence'] = $this->generate_pur_evidence($result[0]['pur_evidence']);
        $results['users']    = PublicdataService::get_user_names();

        //回写质检单凭证单号
        $where_map2 = array(
            'wms_check_quality_details.id'               => array(
                'IN',
                $check_ids
            ),
            'wms_check_quality_details.purchaseorder_id' => $_array['po_id'],
            'print_status'                               => 0
        );
        $data       = array(
            'pur_evidence' => $results['evidence'],
            'print_status' => 1,
        );
        $model->update_check_quality_details($where_map2, $data);

        return $results;
    }

    /**
     * 打印相同采购单下的质检单
     *
     * @param array $_array
     *
     * @return array
     */
    public function print_quality_reports(&$_array = array())
    {
        $model = $this->checkQualityDetails;

        $result  = $this->print_quality_report($_array, true);
        $results = array();
        foreach ($result as $_result) {
            $results[$_result['purchaseorder_id']]['result'][] = $_result;
        }
        foreach ($results as $key => &$_results) {
            $_results['evidence'] = $this->generate_pur_evidence($_results['result'][0]['pur_evidence']);
            //回写质检单凭证单号
            $check_ids  = explode('-', $_array['ids']);
            $where_map2 = array(
                'wms_check_quality_details.id'               => array(
                    'IN',
                    $check_ids
                ),
                'wms_check_quality_details.purchaseorder_id' => $key,
                'print_status'                               => 0
            );
            $data       = array(
                'pur_evidence' => $_results['evidence'],
                'print_status' => 1,
            );
            $model->update_check_quality_details($where_map2, $data);
        }
        $data['results'] = $results;
        $data['users']   = PublicdataService::get_user_names();
        return $data;
    }

    /**
     * 生成最新的采购凭证单号
     *
     * @return string
     */
    public function generate_pur_evidence($evidence = null)
    {
        if (!$evidence) {
            $time   = date('Ymd');
            $where  = array(
                'pur_evidence' => array(
                    array(
                        'gt',
                        "{$time}"
                    )
                ),
            );
            $model  = $this->checkQualityDetails->get_check_details_model($where);
            $result = $model->field('MAX(`pur_evidence`) AS maxid')
                ->find();
            $max    = $result['maxid'];

            $evidence = '';
            if (empty($max)) {
                $evidence = $time.'0001';
            } else {
                $time1 = substr($max, 0, 8);
                $int   = substr($max, -4);
                if ($time == $time1) {
                    $int = $int + 1;
                    $len = '';
                    for ($i = strlen($int); $i < 4; $i++) {
                        $len .= '0';
                    }
                    $evidence = $time.$len.$int;
                } else {
                    $evidence = $time.'0001';
                }
            }
        }

        return $evidence;
    }

    /**
     * 导出csv
     *
     * @param      $datas
     */
    public function down_check_details_csv($datas)
    {
        //取消指定时间限制(在导出的函数入口设置，这是合理的，导出的数据量过大了)
        set_time_limit(0);
        ini_set('memory_limit', '1024M');//此处限制1G内存；请根据实际情况设定
        //为fputcsv()函数打开文件句柄
        $output = fopen('php://output', 'w') or die("can't open php://output");
        //告诉浏览器这个是一个csv文件
        $filename = "质检明细报表".date('Y-m-d', time());
        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$filename.csv");

        ob_end_clean();//关闭缓冲区，当数据量大时，事实证明很有效
        //输出表头
        $table_head = array(
            '站点','质检日期','采购单号', '公司主体', '是否出口退税', '收货明细单号', 'SKU', '采购名称', '报关品名', '储位','规格',
            '采购数量', '质检数量','合格数量','不合格数量', '良品率',
            '入库量','供应商','所属仓库',/*'质检标准',*/'质检员'
        );


        fputcsv($output, $table_head);
        // 逐行取出数据，不浪费内存
        $sites = PublicInfoService::get_site_array();
        foreach ($datas['result'] as $key => $val) {
            //将数组内容按顺序输出
            $output_line   = array();
            $output_line[] = $sites[$val['site_id']];
            $output_line[] = $val['invoice_date'];
            $output_line[] = $val['purchaseorder_id'];
            $output_line[] = $datas['enterprise_dominant'][$val['enterprise_dominant']];
            $output_line[] = $datas['rebate'][$val['export_tax_rebate']];
            $output_line[] = $val['recieve_detail_id'];
            $output_line[] = $val['sku'];
            $output_line[] = str_replace(array("\r\n", "\r", "\n", '<br/>', '<br>'), '', $val['sku_name']);
            $output_line[] = $val['item'];
            $output_line[] = $val['storage_position'];
            $output_line[] = $val['sku_standard'];
            $output_line[] = $val['quantity'];
            $output_line[] = $val['check_quantity'];
            $output_line[] = $val['qualified_quantity'];
            $output_line[] = $val['unquality_count'];
            $output_line[] = round($val['qualified_quantity'] / $val['check_quantity'] * 100, 2).'%';

            $output_line[] = $val['qualified_quantity'];
            $output_line[] = $datas['suppliers'][$val['supplier_id']];
            $output_line[] = PublicdataService::get_transfer_hopper_name($val['transfer_hopper_id']);
            //            $output_line[] = PublicdataService::getStandardFromSku($val['sku']);
            $output_line[] = PublicdataService::get_user_name($val['check_man']);
            fputcsv($output, array_values($output_line));
            unset($output_line);
        }
        //关闭文件句柄
        fclose($output) or die("can't close php://output");
        exit;
    }


}
